// pages/volunteer/checkin.js
Page({
  data: {
    // 签到统计
    checkinStats: {
      continuousDays: 0,
      totalPoints: 0
    },
    todayPoints: 5,
    currentDate: '',
    currentMonth: '',
    
    // 签到状态
    checkinStatus: {
      checkedIn: false,
      text: '今日还未签到',
      time: ''
    },
    
    // 日历相关
    weekdays: ['日', '一', '二', '三', '四', '五', '六'],
    calendarDays: [],
    currentYear: new Date().getFullYear(),
    currentMonthIndex: new Date().getMonth(),
    
    // 签到奖励
    rewardsList: [
      { day: 1, points: 5, description: '连续签到1天', canClaim: false, claimed: false },
      { day: 3, points: 15, description: '连续签到3天', canClaim: false, claimed: false },
      { day: 7, points: 50, description: '连续签到7天', canClaim: false, claimed: false },
      { day: 15, points: 100, description: '连续签到15天', canClaim: false, claimed: false },
      { day: 30, points: 300, description: '连续签到30天', canClaim: false, claimed: false }
    ],
    
    // 签到记录
    recentRecords: []
  },

  onLoad(options) {
    this.initPage();
  },

  onShow() {
    this.loadCheckinData();
  },

  // 初始化页面
  initPage() {
    this.updateCurrentDate();
    this.generateCalendar();
    this.loadCheckinData();
  },

  // 更新当前日期
  updateCurrentDate() {
    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth() + 1;
    const date = now.getDate();
    
    this.setData({
      currentDate: `${year}年${month}月${date}日`,
      currentMonth: `${year}年${month}月`,
      currentYear: year,
      currentMonthIndex: now.getMonth()
    });
  },

  // 生成日历
  generateCalendar() {
    const year = this.data.currentYear;
    const month = this.data.currentMonthIndex;
    const firstDay = new Date(year, month, 1);
    const lastDay = new Date(year, month + 1, 0);
    const startDate = new Date(firstDay);
    startDate.setDate(startDate.getDate() - firstDay.getDay());
    
    const days = [];
    const today = new Date();
    
    for (let i = 0; i < 42; i++) {
      const currentDate = new Date(startDate);
      currentDate.setDate(startDate.getDate() + i);
      
      const isToday = currentDate.toDateString() === today.toDateString();
      const isOtherMonth = currentDate.getMonth() !== month;
      const isChecked = this.isDateChecked(currentDate);
      
      days.push({
        date: currentDate.toISOString().split('T')[0],
        day: currentDate.getDate(),
        isToday,
        isOtherMonth,
        isChecked
      });
    }
    
    this.setData({ calendarDays: days });
  },

  // 检查日期是否已签到
  isDateChecked(date) {
    const checkinRecords = wx.getStorageSync('checkinRecords') || [];
    const dateStr = date.toISOString().split('T')[0];
    return checkinRecords.some(record => record.date === dateStr);
  },

  // 加载签到数据
  loadCheckinData() {
    const checkinRecords = wx.getStorageSync('checkinRecords') || [];
    const today = new Date().toISOString().split('T')[0];
    const todayRecord = checkinRecords.find(record => record.date === today);
    
    // 计算连续签到天数
    const continuousDays = this.calculateContinuousDays(checkinRecords);
    
    // 计算总积分
    const totalPoints = checkinRecords.reduce((sum, record) => sum + record.points, 0);
    
    // 更新签到状态
    const checkinStatus = {
      checkedIn: !!todayRecord,
      text: todayRecord ? '今日已签到' : '今日还未签到',
      time: todayRecord ? todayRecord.time : ''
    };
    
    // 更新奖励状态
    const rewardsList = this.data.rewardsList.map(reward => ({
      ...reward,
      canClaim: continuousDays >= reward.day && !reward.claimed,
      claimed: this.isRewardClaimed(reward.day)
    }));
    
    // 获取最近记录
    const recentRecords = checkinRecords.slice(-5).reverse();
    
    this.setData({
      checkinStats: { continuousDays, totalPoints },
      checkinStatus,
      rewardsList,
      recentRecords
    });
  },

  // 计算连续签到天数
  calculateContinuousDays(records) {
    if (records.length === 0) return 0;
    
    const sortedRecords = records.sort((a, b) => new Date(b.date) - new Date(a.date));
    let continuousDays = 0;
    let currentDate = new Date();
    
    for (let i = 0; i < sortedRecords.length; i++) {
      const recordDate = new Date(sortedRecords[i].date);
      const diffDays = Math.floor((currentDate - recordDate) / (1000 * 60 * 60 * 24));
      
      if (diffDays === continuousDays) {
        continuousDays++;
        currentDate = recordDate;
      } else {
        break;
      }
    }
    
    return continuousDays;
  },

  // 检查奖励是否已领取
  isRewardClaimed(day) {
    const claimedRewards = wx.getStorageSync('claimedRewards') || [];
    return claimedRewards.includes(day);
  },

  // 处理签到
  handleCheckin() {
    if (this.data.checkinStatus.checkedIn) {
      wx.showToast({
        title: '今日已签到',
        icon: 'none'
      });
      return;
    }
    
    wx.showLoading({ title: '签到中...' });
    
    // 模拟签到请求
    setTimeout(() => {
      const now = new Date();
      const today = now.toISOString().split('T')[0];
      const time = now.toTimeString().split(' ')[0];
      
      // 保存签到记录
      const checkinRecords = wx.getStorageSync('checkinRecords') || [];
      const newRecord = {
        date: today,
        time: time,
        points: this.data.todayPoints
      };
      checkinRecords.push(newRecord);
      wx.setStorageSync('checkinRecords', checkinRecords);
      
      // 更新用户积分
      const userData = wx.getStorageSync('volunteerUserData') || {};
      userData.currentPoints = (userData.currentPoints || 0) + this.data.todayPoints;
      userData.totalPoints = (userData.totalPoints || 0) + this.data.todayPoints;
      wx.setStorageSync('volunteerUserData', userData);
      
      wx.hideLoading();
      wx.showToast({
        title: `签到成功 +${this.data.todayPoints}积分`,
        icon: 'success'
      });
      
      // 重新加载数据
      this.loadCheckinData();
      this.generateCalendar();
    }, 1000);
  },

  // 领取奖励
  claimReward(e) {
    const day = e.currentTarget.dataset.day;
    const reward = this.data.rewardsList.find(r => r.day === day);
    
    if (!reward || !reward.canClaim || reward.claimed) {
      return;
    }
    
    wx.showLoading({ title: '领取中...' });
    
    setTimeout(() => {
      // 保存已领取的奖励
      const claimedRewards = wx.getStorageSync('claimedRewards') || [];
      claimedRewards.push(day);
      wx.setStorageSync('claimedRewards', claimedRewards);
      
      // 更新用户积分
      const userData = wx.getStorageSync('volunteerUserData') || {};
      userData.currentPoints = (userData.currentPoints || 0) + reward.points;
      userData.totalPoints = (userData.totalPoints || 0) + reward.points;
      wx.setStorageSync('volunteerUserData', userData);
      
      wx.hideLoading();
      wx.showToast({
        title: `领取成功 +${reward.points}积分`,
        icon: 'success'
      });
      
      // 重新加载数据
      this.loadCheckinData();
    }, 1000);
  },

  // 上个月
  prevMonth() {
    let { currentYear, currentMonthIndex } = this.data;
    if (currentMonthIndex === 0) {
      currentMonthIndex = 11;
      currentYear--;
    } else {
      currentMonthIndex--;
    }
    
    this.setData({
      currentYear,
      currentMonthIndex,
      currentMonth: `${currentYear}年${currentMonthIndex + 1}月`
    });
    
    this.generateCalendar();
  },

  // 下个月
  nextMonth() {
    let { currentYear, currentMonthIndex } = this.data;
    if (currentMonthIndex === 11) {
      currentMonthIndex = 0;
      currentYear++;
    } else {
      currentMonthIndex++;
    }
    
    this.setData({
      currentYear,
      currentMonthIndex,
      currentMonth: `${currentYear}年${currentMonthIndex + 1}月`
    });
    
    this.generateCalendar();
  },

  // 查看所有记录
  viewAllRecords() {
    wx.navigateTo({
      url: '/pages/volunteer/checkin-records'
    });
  },

  // 返回
  goBack() {
    wx.navigateBack();
  },

  // 分享
  onShareAppMessage() {
    return {
      title: '每日签到，积少成多',
      path: '/pages/volunteer/checkin',
      imageUrl: '/images/share-checkin.png'
    };
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadCheckinData();
    this.generateCalendar();
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 1000);
  }
});